package com.example.demo.zaqizabatest;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName JavaThreadPool
 * @Author lys4134
 * @Date 2022/03/09 11:03:54
 * @Description JavaThreadPool
 * @Version 1.0
 **/
public class JavaThreadPool {
    private int coreSize;
    private BlockingQueue<Runnable> runnables;
    private boolean shutdownFlag = true;

    public JavaThreadPool(int coreSize, int queueSize) {
        this.runnables = new LinkedBlockingQueue<>(queueSize);
        this.coreSize = coreSize;
        for (int i = 0 ; i < this.coreSize; i++) {
            WorkThread workThread = new WorkThread();
            workThread.setName("线程" + i);
            workThread.start();
        }
    }

    class WorkThread extends Thread {
        @Override
        public void run() {
            while (shutdownFlag || runnables.size() > 0) {
                Runnable runnable = runnables.poll();
                if (runnable != null) {
                    runnable.run();
                }
            }
        }
    }

    public boolean execute(Runnable runnable) {
       return runnables.offer(runnable);
    }

    public void shutdown() {
        this.shutdownFlag = false;
    }

    public static void main(String[] args) {
        //noinspection AlibabaThreadShouldSetName
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(2, 2, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(2));
        JavaThreadPool pool = new JavaThreadPool(2, 4);
        for (int i = 1; i <= 5; i++) {
            int finalI = i;
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + " 在帮我干活" + finalI);
                }
            });
            poolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + " 在帮我干活" + finalI);
                }
            });
        }
//        pool.shutdown();
    }

}
